<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>axupimgs</title>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<link rel="stylesheet" href="/static/admin/component/pear/css/pear.css">
<link rel="stylesheet" href="/static/admin/admin/css/load.css"/>
<link rel="stylesheet" href="/static/admin/admin/css/mystyle.css"/>
<script src="/static/admin/component/layui/layui.js"></script>
<script src="/static/admin/component/pear/pear.js"></script>
</head>
<body >
<div class="layui-tab layui-tab-brief" style="margin: 0px;" lay-filter="docDemoTabBrief">
  <ul class="layui-tab-title" style="">
    <li class="layui-this">本地上传</li>
    <li>图片管理</li><li>视频管理</li><li>音频管理</li>
  </ul>
  <div class="layui-tab-content">
    <div class="layui-tab-item layui-show">
        <div id="wrap">
	<div id="topbar"><button class="addfile primary">+ 添加文件</button><button class="upall primary">全部上传</button><button class="removeall">清空列表</button></div>
	<ul class="file_list" id="file_list"></ul>
</div>
    </div>
    <div class="layui-tab-item file_listload"  style="padding:0 10px; ">
        <ul class="file_list " id="imagelist">
        </ul>
        <div  id="imagelayuipage"></div>
    </div>
       <div class="layui-tab-item file_listload">
            <ul class="file_list " id="videolist">
        </ul>
        <div  id="videolayuipage"></div>
       </div>
    <div class="layui-tab-item file_listload">
         <ul class="file_list " id="audiolist">
        </ul>
        <div  id="audiolayuipage"></div>
    </div>
 <div  id="layuipage"></div>
  </div>
</div>

<script>
    let editor=parent.tinymce.activeEditor;
	let axupimgs=parent.axupimgs;
	axupimgs.res = []; //存放本地文件的数组
	let blobInfo = {file:null}
	blobInfo.blob = function(){return this.file;}
	let upload_handler = axupimgs.images_upload_handler;
	let upload_base_path = axupimgs.images_upload_base_path;
    let getcontentstr=axupimgs.gethtmlstr;
    layui.use(['element','laypage','loading'], function(){
      let $ = layui.jquery
      ,laypage = layui.laypage
      ,element = layui.element //Tab的切换功能，切换事件监听等，需要依赖element模块
      ,loading = layui.loading;
        let page = 1;//当前页
        let limit = 12;//每页显示的数目
        let resCount, resData ;
        let isfirst=[];
        let resPage=null;
        let types='';
        element.on('tab(docDemoTabBrief)', function(data){
            console.log(data.index)
            if (data.index===1) {types="image";if(isfirst.indexOf(1)===-1) { page=1; resPage = renderPage1(); isfirst.push(1) }}
            else if(data.index===2){types="video";if(isfirst.indexOf(2)===-1) {page=1;resPage = renderPage1();isfirst.push(2)}}
            else if(data.index===3){types="audio";if(isfirst.indexOf(3)===-1) {page=1;resPage = renderPage1();isfirst.push(3)}}
            else if(data.index===0){$("#layuipage").hide()}
          });
        //渲染展示商品的html页面
        function renderProductHtml(data){
        	let str = "";//用来存储html内容
        	if(data.length > 0){
	        	$.each(data, function(v, o){
	        		str += '<li class="up-no"  ><div class="tools"><a class="remove2"></a></div>' +
                        '<div class="picbox" id="'+o.id+'" lay-data="'+o.href+'" lay-type="'+o.mime+'" onclick="chooseimg(this)">' +  getcontentstr(o.href,o.mime,false)+
                        '</div><div class="namebox"><span>'+o.name+'</span></div></li>';
	        	});
	        	$("#"+types+"list").html(str);
	        	loading.blockRemove(".file_listload");
        	}
        }
        //同步加载图片
        function renderProduct(page, limit, types){
             loading.block({type:5,elem:'.file_listload',msg:''})
        	$.ajax({
        		async: false,
        		url: '/admin/file/table',
        		data: {"page": page, "limit": limit,'type':types},
        		dataType: 'json',
        		success: function(result){
        			console.info(result);
        			resCount = result.count;
        			resData = result.data;
        			renderProductHtml(resData);
        		}
        	});
        }
        //分页的完整功能
        function renderPage1(){
             renderProduct(page, limit, types);
             laypage.render({
                 elem: types+'layuipage'
                 ,count: resCount
                 ,limit: limit
                 ,limits: [limit]
                 ,curr: page
                 ,theme: '#FFB800'
                 ,layout: ['count', 'prev', 'page', 'next', 'limit']
                 ,jump: function(obj, first){
                       page = obj.curr;
                   if(!first){
                       renderProduct(page, limit, types);
                   }
                 }
               });
        }
    });

	//图库选择图片
	 function chooseimg(e) {
	     let li=e.parentNode;
	     console.log(li);
	     let url=e.getAttribute('lay-data');
	     let mime=e.getAttribute('lay-type');
         if(li.className==="up-no")
         {
             li.setAttribute('class','up-over');
             axupimgs.res.push({file:null,fid:'',blobUrl:'',url:url,mime:mime});
         }
         else
         {li.setAttribute('class','up-no');
         axupimgs.res.splice(url,1);
         }
         console.log(axupimgs.res)
    }
	//为列表添加排序
	function reSort(){
        document.querySelectorAll('#file_list li').forEach((el,i)=>{
            el.setAttribute('data-num',i);
        });
	}
    function addList(files){
        let files_sum = files.length;
        let vDom = document.createDocumentFragment();
        for(let i=0;i<files_sum;i++){
            let file = files[i];
            let blobUrl = window.URL.createObjectURL(file)
            axupimgs.res.push({file:file,fid:file.lastModified,blobUrl:blobUrl,url:'',mime:file.type});
            let li = document.createElement('li');
            //li.setAttribute('class','up-no');
            li.setAttribute('class','up-now');
            li.setAttribute('data-time',file.lastModified);
            li.setAttribute('id',file.lastModified);
            li.innerHTML='<div class="picbox">' +
                 getcontentstr(blobUrl,file.type,true)+ '</div>' +
                    '<div class="progress" id="pro'+i+'"></div>'+
                '<div class="namebox"><span>'+file.name+'</span></div>' +
                '<div class="tools"><a class="remove"></a></div>';
            vDom.appendChild(li);
        }
        document.querySelector('#file_list').appendChild(vDom);
        //reSort();
    }
    //清空列表
    document.querySelector('#topbar .removeall').addEventListener('click',()=>{
        axupimgs.res=[]
        document.querySelectorAll('#file_list li').forEach((el,i)=>{
            el.parentNode.removeChild(el)
        });
    });
    //拖拽添加
    document.addEventListener('dragover', (e)=>{
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    });
    document.addEventListener('drop', (e)=>{
        e.stopPropagation();
        e.preventDefault();
        if(!e.dataTransfer.files){return false;}
        let dropfiles = e.dataTransfer.files;
        if(!(dropfiles.length>0)){return false;}
        let exts=axupimgs.axupimgs_filetype.replace(/(\s)+/g,'').toLowerCase().split(',');
        let files=[];
        let sext;
        for (let file of dropfiles) {
            sext = file.name.split('.');
            //去掉只能拖拽图片限制
            //let ext = '.' + sext[sext.length - 1];
            //for (let s of exts) {
                //if (s === ext) {
                    files.push(file);
                    break;
                //}
            //}
        }
        console.log(dropfiles,exts)
        if(files.length>0){ addList(files) }
    });
    //添加文件
    document.querySelector('#topbar .addfile').addEventListener('click',()=>{
        let input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('multiple', 'multiple');
        input.setAttribute('accept', axupimgs.axupimgs_filetype);
        input.click();
        input.onchange = function() {
            let files = this.files;
            addList(files);
            console.log(axupimgs.res,1)
        }
    });
	let file_i = 0;
	function upAllFiles(n){
		let len = axupimgs.res.length;
		file_i = n;
		if(len === n){
			file_i=0;
            document.querySelector('#topbar .upall').innerText='全部上传';
			return true;
		}

		if( axupimgs.res[n].url!=='' || axupimgs.res[n].blobUrl==='' ){
			n++;
			upAllFiles(n)
		}else{
			blobInfo.file=axupimgs.res[n].file;
			upload_handler(blobInfo,function(data){
			    let url=data.url;
				if(upload_base_path){
					if(upload_base_path.slice(-1)==='/' && url.substr(0,1)==='/' ){
						url = upload_base_path + url.slice(1);
					}else if(upload_base_path.slice(-1)!=='/' && url.substr(0,1)!=='/' ){
						url = upload_base_path + '/' + url;
					}else{
						url = upload_base_path + url;
					}
				}
				axupimgs.res[n].url = url;
				console.log(axupimgs.res[n],9+',,,'+n)
				filename = url.split('/').pop();
                //var li = document.querySelectorAll('#file_list li')[n];
                let li=document.getElementById(axupimgs.res[n].fid);
                li.setAttribute('class','up-over');
				li.querySelector('.namebox span').innerText = filename;
				n++
				upAllFiles(n);
				console.log(axupimgs.res,2)
			},function(err){
                document.querySelector('#topbar .upall').innerText='全部上传';
                document.querySelectorAll('#file_list li.up-now').forEach((el,i)=>{
                    el.setAttribute('class','up-no');
                });
            },function (p) {
			    document.getElementById("pro"+n).style.width=p;
                }
            );
		}
		
	}
    document.querySelector('#topbar .upall').addEventListener('click',(e)=>{
        if(e.target.innerText!=='全部上传'){return false;}
        if(axupimgs.res.length>0){
           // document.querySelectorAll('#file_list li.up-no').forEach((el,i)=>{
               // el.classList ? el.classList.add('up-now') : el.className+=' up-now';
           // });
            e.target.innerText='上传中...';
            upAllFiles(0);
        }
    });
    let observ_flist = new MutationObserver( (muList,observe)=>{
        if(muList[0].addedNodes.length>0){
            muList[0].addedNodes.forEach((el)=>{
                el.querySelector('.remove').addEventListener('click',(e)=>{
                    let li = e.target.parentNode.parentNode;
                    let n = li.getAttribute('data-num');
                    let el = document.querySelectorAll('#file_list li')[n];
                    el.parentNode.removeChild(el);
                    axupimgs.res.splice(n,1);
                });
            });
        }
        reSort();
    });
    observ_flist.observe(document.querySelector('#file_list'),{childList:true});
</script>
</body>
</html>